from app import create_app, db
from app.models import User, Role, Permission, Thesis, Message
from flask_migrate import Migrate
from sqlalchemy import text
from datetime import datetime, timedelta

app = create_app()
migrate = Migrate(app, db)

def init_roles():
    """初始化角色"""
    admin_role = Role.query.filter_by(name='admin').first()
    if not admin_role:
        admin_role = Role(name='admin', description='Administrator')
        admin_role.permissions = Permission.ADMIN
        db.session.add(admin_role)

    user_role = Role.query.filter_by(name='user').first()
    if not user_role:
        user_role = Role(name='user', description='Normal user')
        user_role.permissions = Permission.VIEW | Permission.COMMENT
        db.session.add(user_role)

    db.session.commit()
    return admin_role, user_role

def init_users():
    """初始化默认用户"""
    admin_role, user_role = init_roles()
    
    # 创建管理员账号
    admin = User.query.filter_by(email='admin@admin').first()
    if not admin:
        admin = User(
            username='admin',
            email='admin@admin'
        )
        admin.set_password('admin123')
        admin.roles.append(admin_role)
        db.session.add(admin)
    
    # 创建测试用户账号
    test_user = User.query.filter_by(email='test@test').first()
    if not test_user:
        test_user = User(
            username='test',
            email='test@test'
        )
        test_user.set_password('test123')
        test_user.roles.append(user_role)
        db.session.add(test_user)
    
    db.session.commit()

def init_sample_theses():
    """初始化示例论文数据"""
    test_user = User.query.filter_by(email='test@test').first()
    if not test_user:
        return
    
    # 只有当没有任何论文数据时才添加示例数据
    if Thesis.query.count() == 0:
        sample_theses = [
            {
                'title': '基于Python的学生成绩管理系统',
                'description': '使用Python和Flask框架开发的学生成绩管理系统，包含成绩录入、统计分析、成绩导出等功能。',
                'programming_language': 'Python',
                'price': 700,
                'thesis_type': 'design',
                'contact_info': 'QQ: 123456789',
                'deadline': datetime.now() + timedelta(days=30),
                'need_environment': True,
                'status': 'pending'
            },
            {
                'title': '机器学习在图像识别中的应用研究',
                'description': '研究深度学习在图像识别领域的应用，使用TensorFlow框架实现模型训练和预测。',
                'programming_language': 'Python',
                'price': 1000,
                'thesis_type': 'full',
                'contact_info': '微信: ML_Study',
                'deadline': datetime.now() + timedelta(days=45),
                'need_environment': True,
                'status': 'accepted'
            },
            {
                'title': 'Java Web电商平台开发',
                'description': '基于Spring Boot框架开发的电商平台，包含用户管理、商品管理、订单处理等功能。',
                'programming_language': 'Java',
                'price': 700,
                'thesis_type': 'design',
                'contact_info': 'QQ: 987654321',
                'deadline': datetime.now() + timedelta(days=60),
                'need_environment': False,
                'status': 'completed'
            },
            {
                'title': '区块链技术在供应链金融中的应用',
                'description': '研究区块链技术如何改善供应链金融的效率和安全性，包含智能合约的实现。',
                'programming_language': 'Solidity',
                'price': 500,
                'thesis_type': 'thesis',
                'contact_info': '邮箱: blockchain@example.com',
                'deadline': datetime.now() + timedelta(days=40),
                'need_environment': False,
                'status': 'pending'
            },
            {
                'title': '基于MATLAB的数字信号处理系统',
                'description': '使用MATLAB开发的数字信号处理系统，实现信号采集、滤波、频谱分析等功能。',
                'programming_language': 'MATLAB',
                'price': 1000,
                'thesis_type': 'full',
                'contact_info': 'QQ: 135792468',
                'deadline': datetime.now() + timedelta(days=50),
                'need_environment': True,
                'status': 'accepted'
            }
        ]
        
        for thesis_data in sample_theses:
            thesis = Thesis(
                title=thesis_data['title'],
                description=thesis_data['description'],
                programming_language=thesis_data['programming_language'],
                price=thesis_data['price'],
                thesis_type=thesis_data['thesis_type'],
                contact_info=thesis_data['contact_info'],
                deadline=thesis_data['deadline'],
                need_environment=thesis_data['need_environment'],
                status=thesis_data['status'],
                user=test_user
            )
            db.session.add(thesis)
        
        db.session.commit()

@app.shell_context_processor
def make_shell_context():
    return {
        'db': db, 
        'User': User, 
        'Role': Role, 
        'Permission': Permission, 
        'Thesis': Thesis,
        'Message': Message
    }

if __name__ == '__main__':
    debug = True
    with app.app_context():
        # 初始化数据库
        db.create_all()
        # 初始化角色和用户
        init_users()
        # 初始化示例论文
        init_sample_theses()
        # 修复可能的数据问题
        try:
            db.session.execute(text("UPDATE thesis SET thesis_type = 'design' WHERE thesis_type IS NULL"))
            db.session.commit()
        except Exception as e:
            print(f"Error updating thesis_type: {e}")
            db.session.rollback()
    
    if debug:
        app.run(debug=True)
    else:
        app.run(debug=False, host='0.0.0.0', port=8003)